#coding:utf-8
import config
from nexusphp import NexusPHP
from dl115 import DL115
import time
import urllib2

def printf(str):
    print str.decode('UTF-8').encode('GBK')


pt = NexusPHP()
dl115 = DL115()

if __name__ == "__main__":
    urllib2.socket.setdefaulttimeout(10)
    torrent_add_task_fail = []
    while True:
         try:#try块太长了
            dl115.auto_make_share_link()
            task_count = dl115.get_bt_task_count()
            if task_count < config.DL115_DLMAX:
                #爬取种子到指定目录
                id_list = pt.getTorrent(config.DL115_DLMAX - task_count - len(torrent_add_task_fail))
                for item in torrent_add_task_fail:
                    #将失败重试列表加入重试
                    if item[1] == 0:
                        #addlog
                        item[1] = item[1] - 1
                    else:
                        if item[1] > 0:
                            id_list.append(item[0])
                            item[1] = item[1] - 1
                print id_list
                for id in id_list:
                    #开始加入115离线
                    try:
                        if dl115.upload_torrent(id) ==0:
                            printf(id +  '.torrent 成功加入离线')
                            #从失败列表删除
                            for item in torrent_add_task_fail:
                                if item[0] == id:
                                    torrent_add_task_fail.remove(item)
                                    break
                        else:
                            #加入失败列表
                            flag = 0
                            for item in torrent_add_task_fail:
                                if item[0] == id:
                                    flag = 1
                                    break
                            if(flag == 0):
                                torrent_add_task_fail.append([id, 3])
                    except:
                        #加入失败列表
                        flag = 0
                        for item in torrent_add_task_fail:
                            if item[0] == id:
                                flag = 1
                                break
                        if(flag == 0):
                            torrent_add_task_fail.append([id, 3])
            time.sleep(30)
         except Exception,ex:
            Exception,":",ex
            time.sleep(5)
